package com.fuyd.pms.background.web.account;

import com.fuyd.pms.entity.Merchant;
import com.fuyd.pms.entity.account.MerchantUser;
import com.fuyd.pms.background.service.account.AccountService;
import com.fuyd.pms.background.web.base.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;

/**
 * 用户注册
 * Created by fuyongde on 2015/12/26.
 */
@Controller
@RequestMapping(value = "/register")
public class RegisterController extends BaseController {
    @Autowired
    private AccountService accountService;

    @RequestMapping(method = RequestMethod.GET)
    public String registerForm() {
        return "account/register";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String register(
            @Valid MerchantUser merchantUser,
            @RequestParam(value = "password", required = true) String password,
            RedirectAttributes redirectAttributes
    ) {
        try {
            Merchant merchant = getCurrentUser().getMerchant();
            merchantUser.setMerchant(merchant);
            accountService.registerUser(merchantUser, password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        redirectAttributes.addFlashAttribute("username", merchantUser.getUsername());
        return "redirect:/login";
    }

    /**
     * Ajax请求校验loginName是否唯一。
     */
    @RequestMapping(value = "/checkUsername")
    @ResponseBody
    public String checkLoginName(@RequestParam("username") String username) {
        if (accountService.findLocalAuthByUsername(username) == null) {
            return "true";
        } else {
            return "false";
        }
    }
}
